package slistmgr

import (
	"gameserver/messages"
	"gameserver/server/Login/internal"

	"gitee.com/night-tc/gobige/logger"
)

func (this *ServerListMgr) GetAllWhiteList() []*messages.Whitelist_MD {
	this.whitelock.RLock()
	defer this.whitelock.RUnlock()
	return this.whitelist
}

// 设置白名单 为玩家的信息
func (this *ServerListMgr) SetOneWhiteList(md *messages.Whitelist_MD) *messages.Whitelist_MD {
	err := this.setwhite(md)
	if err != nil {
		logger.Error("setwhite error:", err)
		return nil
	}

	this.LoadWhite()
	return md
}

func (this *ServerListMgr) SetMultiWhiteList(li []*messages.Whitelist_MD) {
	for _, md := range li {
		err := this.setwhite(md)
		if err != nil {
			logger.Error("setwhite error:", err)
		}
	}
	this.LoadWhite()
}

func (this *ServerListMgr) setwhite(md *messages.Whitelist_MD) error {
	db := internal.GetSrvinst().GetMysqlMgr()

	queryDb := db.Model(md).Where("wtype=?", md.WhiteListType)
	switch md.WhiteListType {
	case messages.WhiteListTypeEnum_TypeUserID:
		if db := queryDb.Where("uid=?", md.UserId).Take(md); db.Error == nil && md.Id != 0 {
			return nil
		}
		db := db.Model(md).Create(md)
		if db.Error != nil {
			return db.Error
		}
	case messages.WhiteListTypeEnum_TypeOpenID:
		if db := queryDb.Where("openId=? and channelId=?", md.OpenID, md.ChannelID).Take(md); db.Error == nil && md.Id != 0 {
			return nil
		}
		db := db.Model(md).Create(md)
		if db.Error != nil {
			return db.Error
		}
	case messages.WhiteListTypeEnum_TypeDeviceInfo:
		if db := queryDb.Where("deviceId=?", md.DeviceInfo).Take(md); db.Error == nil && md.Id != 0 {
			return nil
		}
		db := db.Model(md).Create(md)
		if db.Error != nil {
			return db.Error
		}
	default:
		logger.Error("Operation not impl!")
		return nil
	}
	return nil
}

// 删除白名单数据
func (this *ServerListMgr) DeleteWhiteList(ids []uint64) (affectedNum int64) {
	db := internal.GetSrvinst().GetMysqlMgr().Model(&messages.Whitelist_MD{}).Where("id in ?", ids).Delete(nil)
	affectedNum = db.RowsAffected
	this.LoadWhite()
	return
}
